var utils = require("../Utils/utils")
var model = require("../DAO/model")
var express = require('express')
var md5 = require("md5")
var indexDao = require("../DAO/indexDao")

var router = express.Router();

var session = require('express-session')

//获取首页
router.get("/", function(req, res) {

	if(req.session.userInfo !== undefined && req.session.userInfo !== null) {
		indexDao.getUserByEmail(req.session.userInfo.email, function(err, doc) {
			if(!err) {
				req.session.userInfo.name = doc.name
				req.session.userInfo.avatar = doc.avatar
				res.render("index.html", {
					title: "index",
					loc: "index",
					isLogin: req.session.userInfo.isLogin,
					name: req.session.userInfo.name,
					avatar: req.session.userInfo.avatar
				})
			} else {
				res.send("服务器错误！")
			}
		})

	} else {
		res.render("index.html", {
			title: "index",
			loc: "index"
		})
	}

})
//获取注册页面
router.get("/register/login", function(req, res) {
	res.render("register_login.html", {
		title: "register",
		loc: "register"
	})
})

//注册接口
router.post("/register", function(req, res) {

	indexDao.getUserByEmail(req.body.email, function(err, doc) {
		if(!err) {
			if(doc == null) {
				req.body.createTime = utils.getTime();
				req.body.password = md5(md5(req.body.password))
				var user  = req.body
				indexDao.saveOneUser(user, function(err) {
					if(err) {
						res.send({
							info: "服务器出错！"
						})
						return
					}
					res.send({
						info: "注册成功!"
					})
					return
				})

			} else {
				console.log("用户已存在")
				res.send({
					info: "用户已存在"
				})
				return
			}
		} else {
			console.log("数据库查询失败！")
		}
	})

})

//获取登陆页面
router.get("/login", indexDao.getLoginPage)

//登陆接口
router.post("/login", indexDao.login)

//获取标签页面
router.get("/tag", indexDao.getTagPage)

router.get("/userConfig", indexDao.getConfigPage)

//注销
router.get("/logout", indexDao.getLogoutPage)

module.exports = router